import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';

class RecordsScreen extends StatefulWidget {
  const RecordsScreen({Key? key}) : super(key: key);

  @override
  _RecordsScreenState createState() => _RecordsScreenState();
}

class _RecordsScreenState extends State<RecordsScreen> {
  final _refreshKey = GlobalKey<RefreshIndicatorState>();
  RecordType? _selectedType;
  DateTime? _startDate;
  DateTime? _endDate;

  @override
  void initState() {
    super.initState();
    _startDate = DateTime.now().subtract(const Duration(days: 7));
    _endDate = DateTime.now();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('健康记录'),
        actions: [
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: _showFilterDialog,
          ),
        ],
      ),
      body: RefreshIndicator(
        key: _refreshKey,
        onRefresh: () async {
          setState(() {});
        },
        child: FutureBuilder<List<HealthRecord>>(
          future: DatabaseService().getHealthRecords(
            type: _selectedType,
            startDate: _startDate,
            endDate: _endDate,
          ),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Center(child: Text('加载失败: ${snapshot.error}'));
            }

            if (!snapshot.hasData) {
              return const Center(child: CircularProgressIndicator());
            }

            final records = snapshot.data!;
            if (records.isEmpty) {
              return const Center(child: Text('暂无记录'));
            }

            return ListView.builder(
              itemCount: records.length,
              itemBuilder: (context, index) {
                final record = records[index];
                return ListTile(
                  leading: _getRecordTypeIcon(record.type),
                  title: Text(_getRecordTypeText(record.type)),
                  subtitle: Text(_formatRecordData(record)),
                  trailing: Text(
                    DateFormat('MM-dd HH:mm').format(record.timestamp),
                  ),
                  onTap: () => _showRecordDetails(record),
                );
              },
            );
          },
        ),
      ),
    );
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('筛选记录'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                DropdownButton<RecordType?>(
                  value: _selectedType,
                  items: [
                    const DropdownMenuItem(value: null, child: Text('全部类型')),
                    ...RecordType.values.map(
                      (type) => DropdownMenuItem(
                        value: type,
                        child: Text(_getRecordTypeText(type)),
                      ),
                    ),
                  ],
                  onChanged: (value) {
                    setState(() => _selectedType = value);
                    Navigator.pop(context);
                  },
                ),
                const SizedBox(height: 16),
                Row(
                  children: [
                    TextButton(
                      onPressed: () async {
                        final dateRange = await showDateRangePicker(
                          context: context,
                          firstDate: DateTime(2020),
                          lastDate: DateTime.now(),
                          initialDateRange: DateTimeRange(
                            start: _startDate!,
                            end: _endDate!,
                          ),
                        );
                        if (dateRange != null) {
                          setState(() {
                            _startDate = dateRange.start;
                            _endDate = dateRange.end;
                          });
                          Navigator.pop(context);
                        }
                      },
                      child: Text('选择日期范围'),
                    ),
                  ],
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () {
                  setState(() {
                    _selectedType = null;
                    _startDate = DateTime.now().subtract(
                      const Duration(days: 7),
                    );
                    _endDate = DateTime.now();
                  });
                  Navigator.pop(context);
                },
                child: const Text('重置'),
              ),
            ],
          ),
    );
  }

  void _showRecordDetails(HealthRecord record) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text(_getRecordTypeText(record.type)),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '时间: ${DateFormat('yyyy-MM-dd HH:mm').format(record.timestamp)}',
                ),
                const SizedBox(height: 8),
                Text('详细信息: ${_formatRecordData(record)}'),
                if (record.data['notes'] != null) ...[
                  const SizedBox(height: 8),
                  Text('备注: ${record.data['notes']}'),
                ],
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ],
          ),
    );
  }

  Icon _getRecordTypeIcon(RecordType type) {
    switch (type) {
      case RecordType.feeding:
        return const Icon(Icons.baby_changing_station);
      case RecordType.diaper:
        return const Icon(Icons.cleaning_services);
      case RecordType.sleep:
        return const Icon(Icons.bedtime);
      case RecordType.temperature:
        return const Icon(Icons.thermostat);
      default:
        return const Icon(Icons.event_note);
    }
  }

  String _getRecordTypeText(RecordType type) {
    switch (type) {
      case RecordType.feeding:
        return '喂奶';
      case RecordType.diaper:
        return '换尿布';
      case RecordType.sleep:
        return '睡眠';
      case RecordType.temperature:
        return '体温';
      default:
        return '其他';
    }
  }

  String _formatRecordData(HealthRecord record) {
    switch (record.type) {
      case RecordType.feeding:
        return '${record.data['amount']}ml';
      case RecordType.diaper:
        return record.data['type'] == 'wet' ? '尿尿' : '便便';
      case RecordType.sleep:
        return '${record.data['duration']}分钟';
      case RecordType.temperature:
        return '${record.data['temperature']}°C';
      default:
        return '';
    }
  }
}
